import Axios from 'axios';
import {stringToNumber,arrayToString} from '@/utils/index'
import {baseUrl} from '@/api/index'
/**
 * 请求的集中配置
 */
Axios.defaults.baseURL = baseUrl;
Axios.defaults.timeout = 30000;

Axios.defaults.headers = {
    'Content-Type': 'application/json'
};
const Authorization = localStorage.getItem('TOKEN') || null;
Axios.defaults.headers.common = { Authorization };
Axios.interceptors.request.use((config) => {
    if (config.method === 'get') {
        config.params = arrayToString(config.params);
    }
    if (config.url.includes('download') && !config.url.includes('download/getlist')) {
        config.timeout = 300;
    }
    return config;
});

Axios.interceptors.response.use(
    (res) => {
        console.log(res);
        if (res.data.code !== 200 && res.data.code !== 1) {
            if (res.data.code === 403) {
                this.$router.replace({
                    name: 'Login'
                });
            } else {
                this.$message.error(res.data.msg || '服务器发生错误，请稍后再试。');
            }
            return Promise.reject(res);
        } else {
            console.log('header')
            console.log(res.headers)
            if (res.headers.authorization) {
                localStorage.setItem('TOKEN', res.headers.authorization);
                Axios.defaults.headers.common.Authorization = res.headers.authorization;
            }
            res.data.data = stringToNumber(res.data.data);
            return res.data;
        }
    },
    (err) => {
        console.log(err.config);
        if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
            if (err.config.url.includes('download')) {
                return {
                    data: {
                        code: 200
                    }
                };
            } else {
                this.$message.error('请求超时，请稍后再试。');
                return Promise.reject(err);
            }
        } else {
            this.$message.error('服务器发生错误，请稍后再试。');
            return Promise.reject(err);
        }
    }
);
export default Axios;
